﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using ChatApp.Core.Business;
using ChatApp.Core.Info;

namespace ChatApp.Core.Facade
{
    public class MessageFacade : IMessageFacade
    {
        IMessageBusiness aMessageBusiness = new MessageBusiness();
        public void InsertMessage(MessageInfo pMessageInfo)
        {
           aMessageBusiness.Insert(pMessageInfo);
        }

        public IList<MessageInfo> getConversation(int toUserId, int fromUserId)
        {
            var lParam = new List<ParameterInfo>();
            lParam.Add(new ParameterInfo(){Name = "UserIdTo", Value = toUserId});
            lParam.Add(new ParameterInfo() { Name = "UserIdFrom", Value = fromUserId });
            return aMessageBusiness.SelectByParams(lParam);
        }

        public void UpdateMessage(object fromUserId, object toUserId)
        {
            var aUserFacade = new UserFacade();
            var aUserInforTo = aUserFacade.getUser(toUserId.ToString());
            var aUserInforFrom = aUserFacade.getUser(fromUserId.ToString());
            var aParameter = new List<ParameterInfo>();
            aParameter.Add(new ParameterInfo() { Name = "UserIdTo", Value = aUserInforTo .UserId});
            aParameter.Add(new ParameterInfo() { Name = "UserIdFrom", Value = aUserInforFrom.UserId });
            aParameter.Add(new ParameterInfo() { Name = "is_read", Value = false });
            var lMessageInfo = aMessageBusiness.SelectByParams(aParameter);
            foreach (var pMessageInfo in lMessageInfo)
            {
                pMessageInfo.is_read = true;
                aMessageBusiness.Update(pMessageInfo);
            }
        }

        public IList<UserInfo> CountMessageNoneRead(object userToId)
        {
            var aParameter = new List<ParameterInfo>();
            aParameter.Add(new ParameterInfo() { Name = "is_read", Value = false });
            aParameter.Add(new ParameterInfo() { Name = "UserIdTo", Value = userToId });
            var lMessage = aMessageBusiness.SelectByParams(aParameter);
            var lMessageInfo = lMessage.Select(x => x.UserIdFrom).Distinct().ToList();
            var lUserInfor = new List<UserInfo>();
            var aUserBusiness = new UserBusiness();
            foreach (var aUserFromId in lMessageInfo)
            {
                lUserInfor.Add(aUserBusiness.SelectByPrimaryId(aUserFromId));
            }
            return lUserInfor;
        }
    }
}
